<?php

namespace app\admin\controller\statistics;

use app\common\controller\Backend;
use think\Db;

class Statistics extends Backend
{
    protected $model = null;
    protected $noNeedLogin = ['installMenu'];
    protected $noNeedRight = ['installMenu'];



    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Statistics');
        $this->assignconfig('admin', $_SESSION['think']['admin'] ?? []);
    }

    public function index()
    {
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            try {
                $this->model->allowField(true)->save($params);
                return json(['code' => 200, 'msg' => __('OK')]);
            } catch (\Exception $e) {
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            return json(['code' => 0, 'msg' => __('No Results were found')]);
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            try {
                $row->allowField(true)->save($params);
                return json(['code' => 200, 'msg' => __('OK')]);
            } catch (\Exception $e) {
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    public function installMenu()
    {
        file_put_contents($_SERVER["DOCUMENT_ROOT"]."/../runtime/log/statistics_install_menu.log", date('Y-m-d H:i:s')." installMenu\n", FILE_APPEND);
        $menu = [
            ['name' => 'statistics/statistics/index', 'title' => '数据统计', 'icon' => 'fa fa-bar-chart', 'ismenu' => 1],
            ['name' => 'statistics/statistics/add', 'title' => '添加', 'ismenu' => 0],
            ['name' => 'statistics/statistics/edit', 'title' => '编辑', 'ismenu' => 0],
            ['name' => 'statistics/statistics/del', 'title' => '删除', 'ismenu' => 0],
            ['name' => 'statistics/statistics/multi', 'title' => '批量更新', 'ismenu' => 0],
            ['name' => 'statistics/statistics/recyclebin', 'title' => '回收站', 'ismenu' => 0],
            ['name' => 'statistics/statistics/restore', 'title' => '还原', 'ismenu' => 0],
            ['name' => 'statistics/statistics/import', 'title' => '导入', 'ismenu' => 0],
            ['name' => 'statistics/statistics/export', 'title' => '导出', 'ismenu' => 0],
        ];
        foreach ($menu as $item) {
            $exists = \think\Db::name('auth_rule')->where('name', $item['name'])->find();
            if (!$exists) {
                $data = [
                    'pid' => 0,
                    'name' => $item['name'],
                    'title' => $item['title'],
                    'icon' => isset($item['icon']) ? $item['icon'] : '',
                    'condition' => '',
                    'ismenu' => $item['ismenu'],
                    'status' => 1,
                    'weigh' => 100,
                    'createtime' => time(),
                    'updatetime' => time(),
                ];
                \think\Db::name('auth_rule')->insert($data);
            } else {
                \think\Db::name('auth_rule')->where('id', $exists['id'])->update([
                    'title' => $item['title'],
                    'icon' => isset($item['icon']) ? $item['icon'] : $exists['icon'],
                    'ismenu' => $item['ismenu'],
                    'updatetime' => time(),
                ]);
            }
        }
        $indexRule = \think\Db::name('auth_rule')->where('name', 'statistics/statistics/index')->find();
        if ($indexRule) {
            $childNames = ['statistics/statistics/add','statistics/statistics/edit','statistics/statistics/del','statistics/statistics/multi','statistics/statistics/recyclebin','statistics/statistics/restore','statistics/statistics/import','statistics/statistics/export'];
            \think\Db::name('auth_rule')->where('name','in',$childNames)->update(['pid' => $indexRule['id'], 'updatetime' => time()]);
            $ids = \think\Db::name('auth_rule')->where('name','like','statistics/statistics/%')->column('id');
            foreach ([2,3] as $gid) {
                $group = \think\Db::name('auth_group')->where('id', $gid)->find();
                if ($group) {
                    $set = [];
                    if (!empty($group['rules'])) { $set = array_filter(explode(',', $group['rules'])); }
                    $set = array_unique(array_merge($set, $ids));
                    \think\Db::name('auth_group')->where('id', $gid)->update(['rules' => implode(',', $set), 'updatetime' => time()]);
                }
            }
        }
        return json(['code' => 200, 'msg' => 'OK']);
    }
}